#load the libraries
library('SDMTools')

#set the working directory
in.dir = '/home1/99/jc152199/GRASS/output'
setwd(in.dir)

#get a list of files
filelist = list.files(in.dir, pattern='txt')

#cycle through each of the files
for (tfile in filelist) # NB: Use grass ASCII output without header

		{
  
	  #create the name for the ascii grid file
	  ascname = gsub(".txt","",tfile)
	  
	  #read in the datafile
	  indata = read.table(tfile,header=F)

	  #transpose indata
	  indata=t(as.matrix(indata))
	  
	  #invert the matrix
	  indata = indata[,c(ncol(indata):1)]
	  
	  #convert matrix to asc grid file
	  outdata = as.asc(x=indata,xll=140,yll=-22,cellsize=.0025)
	  
	  #export the ascii grid file
	  write.asc.gz(outdata,file=ascname)

	  }
